﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Runtime.Remoting.Contexts;
using System.IO;
using System.Xml;

namespace DataAccess
{
    [Synchronization]
    public class ConnectionManager
    {
        private volatile static ConnectionManager uniqueInstance;
        private static string strConfigFilePath = "database.config";

        private ConnectionManager() { }

        public static ConnectionManager getInstance()
        {
            if (uniqueInstance == null)
            {
                uniqueInstance = new ConnectionManager();
            }
            return uniqueInstance;
        }

        public SqlConnection getConnection()
        {
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = getConnectionString();
            conn.Open();
            return conn;
        }

        private static string getConnectionString()
        {
            if (!System.IO.File.Exists(strConfigFilePath))
            {
                throw new Exception("配置文件不存在，请先运行数据库配置程序进行配置!");
            }
            FileStream xmlFileStream = new FileStream(strConfigFilePath, FileMode.Open);
            XmlTextReader reader = new XmlTextReader(xmlFileStream);
            
            string strReturn = String.Format("uid={2}; pwd={3}; Initial Catalog={1}; Data Source={0}",
                                ReadXMLbyXMLReader(reader, "ServerIP"),
                                ReadXMLbyXMLReader(reader, "DBName"),
                                ReadXMLbyXMLReader(reader, "LoginUser"),
                                ReadXMLbyXMLReader(reader, "Password"));
            reader.Close();
            xmlFileStream.Close();
            return strReturn;
        }

        private static string ReadXMLbyXMLReader(System.Xml.XmlTextReader reader, string key)
        {
            while (reader.Read())
            {
                if (reader.Name == key)
                {
                    break;
                }
            }
            if (reader.Name == key && reader.Read() && reader.NodeType == XmlNodeType.Text)
                return reader.Value;
            else
                return "";
        }
    }
}
